package com.akuhome.resource.service;

import com.akuhome.resource.entity.Project;
import com.akuhome.resource.enums.ProjectStatus;
import com.akuhome.resource.job.AddCheckJob;
import com.akuhome.resource.job.QuartzBean;
import com.akuhome.resource.job.UpdateProjectStatusJob;
import com.akuhome.resource.service.check.ProjectCheckService;
import com.akuhome.resource.service.entity.ProjectService;
import com.akuhome.resource.util.QuartzUtil;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

@Service
public class QuartzService {
    Logger logger = LoggerFactory.getLogger(QuartzService.class);

    @Autowired
    ProjectService projectService;
    @Autowired
    ProjectCheckService checkService;

    @Autowired
    Scheduler scheduler;

    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public void addUpdateProjectStatusJob(Project project){
        logger.info("正在为项目uid"+project.getUid()+"的项目添加定时任务:更新项目状态");
        logger.info("生效时间预期为:"+format.format(project.getStartDate()));
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("uid",project.getUid());
        dataMap.put("projectStatus",ProjectStatus.COMPLETE);

        QuartzBean start = new QuartzBean();
        start.setJobName(project.getUid()+"start");
        start.setJobClass(UpdateProjectStatusJob.class);
        start.setStartDate(project.getStartDate());//项目开始时触发
        start.setJobDataMap(dataMap);

        QuartzUtil.createScheduleJobOnce(scheduler,start);//仅执行一次
    }

    public void addAddCheckJob(Project project){
        logger.info("正在为项目uid"+project.getUid()+"的项目添加定时任务:添加结算报表");
        logger.info("生效时间预期为:"+format.format(project.getEndDate()));
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("uid",project.getUid());

        QuartzBean end = new QuartzBean();
        end.setJobName(project.getUid()+"end");
        end.setJobClass(AddCheckJob.class);
        end.setStartDate(project.getEndDate());
        end.setJobDataMap(dataMap);

        QuartzUtil.createScheduleJobOnce(scheduler,end);
    }
}
